// 路由处理函数模块
// 导入数据库操作模块
const db = require('../db/index')

// 获取留言内容
exports.getArticlesContent = (req, res) => {
    const sql = 'SELECT content FROM blog_articles ORDER BY likes DESC';
    db.query(sql, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        res.send({
            status: 0,
            message: '获取留言数据成功',
            data: results
        })
    })
}

// 获取留言列表模块
exports.getArticles = (req, res) => {
    const sql = 'SELECT * FROM blog_articles ORDER BY likes DESC';
    db.query(sql, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        res.send({
            status: 0,
            message: '获取留言数据成功',
            data: results
        })
    })
}

// 添加留言
exports.addArticles = (req, res) => {
    const { title, content, author_id } = req.body;
    if (!title || !content || !author_id) {
        return res.cc('标题、内容和作者ID不能为空');
    }

    const sql = 'INSERT INTO blog_articles (title, content, author_id) VALUES (?, ?, ?)';
    db.query(sql, [title, content, author_id], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        if (results.affectedRows !== 1) {
            return res.cc('添加留言失败');
        }
        res.send({
            status: 0,
            message: '添加留言成功'
        });
    });
}

// 点赞留言
exports.LikeArticle = (req, res) => {
    const articleId = req.body.articleId;
    if (!articleId) {
        return res.cc('留言ID不能为空')
    }

    const sql = 'UPDATE blog_articles SET likes = likes + 1 WHERE article_id = ?';
    db.query(sql, [articleId], (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.affectedRows !== 1) {
            return res.cc('点赞失败，留言ID不存在')
        }
        res.send({
            status: 0,
            message: '点赞成功'
        })
    })
}

// 获取留言对应的评论区
exports.getComments = (req, res) => {
    const articleId = req.query.articleId;
    if (!articleId) {
        return res.cc('留言ID不能为空')
    }

    const sql = `
        SELECT 
            c1.comment_id,
            c1.article_id,
            c1.user_id,
            c1.content,
            c1.likes,
            c1.parent_comment_id,
            c1.timestamp,
            u.username,
            u.nickname
        FROM 
            blog_comments c1
        LEFT JOIN 
            blog_users u ON c1.user_id = u.id
        WHERE 
            c1.article_id = ?
        ORDER BY 
            CASE 
                WHEN c1.parent_comment_id IS NULL THEN c1.likes 
                ELSE (SELECT likes FROM blog_comments WHERE comment_id = c1.parent_comment_id) 
            END DESC, 
            c1.parent_comment_id, 
            c1.likes DESC;
    `;

    db.query(sql, [articleId], (err, results) => {
        if (err) {
            return res.cc(err)
        }
        res.send({
            status: 0,
            message: '获取评论数据成功',
            data: results
        })
    })
}

// 点赞评论
exports.LikeComment = (req, res) => {
    const commentId = req.body.commentId;
    if (!commentId) {
        return res.cc('评论ID不能为空')
    }

    const sql = 'UPDATE blog_comments SET likes = likes + 1 WHERE comment_id =?';
    db.query(sql, [commentId], (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.affectedRows !== 1) {
            return res.cc('点赞失败，评论ID不存在')
        }
        res.send({
            status: 0,
            message: '点赞成功'
        })
    })
}

// 添加评论
exports.addComments = (req, res) => {
    const { article_id, user_id, content, parent_comment_id } = req.body;
    if (!article_id || !user_id || !content) {
        return res.cc('留言ID、用户ID和内容不能为空');
    }

    const sql = 'INSERT INTO blog_comments (article_id, user_id, content, parent_comment_id) VALUES (?, ?, ?, ?)';
    db.query(sql, [article_id, user_id, content, parent_comment_id || null], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        if (results.affectedRows !== 1) {
            return res.cc('添加评论失败');
        }
        res.send({
            status: 0,
            message: '添加评论成功'
        });
    });
}

// 递归删除评论
const deleteCommentsRecursively = (commentId, callback) => {
    const sqlGetChildren = 'SELECT comment_id FROM blog_comments WHERE parent_comment_id = ?';
    db.query(sqlGetChildren, [commentId], (err, results) => {
        if (err) {
            return callback(err);
        }

        const children = results.map(row => row.comment_id);
        let remaining = children.length;

        if (remaining === 0) {
            const sqlDeleteComment = 'DELETE FROM blog_comments WHERE comment_id = ?';
            db.query(sqlDeleteComment, [commentId], callback);
        } else {
            children.forEach(childId => {
                deleteCommentsRecursively(childId, (err) => {
                    if (err) {
                        return callback(err);
                    }
                    remaining--;
                    if (remaining === 0) {
                        const sqlDeleteComment = 'DELETE FROM blog_comments WHERE comment_id = ?';
                        db.query(sqlDeleteComment, [commentId], callback);
                    }
                });
            });
        }
    });
}

// 删除留言
exports.deleteArt = (req, res) => {
    const { articleId, username } = req.body; // 使用username代替userId
    if (!articleId || !username) {
        return res.cc('留言ID和用户名不能为空');
    }

    // 查询留言作者ID
    const sqlCheckAuthor = 'SELECT author_id FROM blog_articles WHERE article_id = ?';
    db.query(sqlCheckAuthor, [articleId], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        if (results.length !== 1) {
            return res.cc('留言不存在');
        }

        const authorId = results[0].author_id;

        // 验证用户身份：留言作者 或 blog_users 表中 ID 小于 10 的用户
        const sqlCheckUser = 'SELECT id FROM blog_users WHERE username = ? AND (id < 10 OR id = ?)';
        db.query(sqlCheckUser, [username, authorId], (err, results) => {
            if (err) {
                return res.cc(err);
            }
            if (results.length !== 1) {
                return res.cc('没有删除权限');
            }

            // 先递归删除留言的所有评论
            const sqlGetComments = 'SELECT comment_id FROM blog_comments WHERE article_id = ? AND parent_comment_id IS NULL';
            db.query(sqlGetComments, [articleId], (err, results) => {
                if (err) {
                    return res.cc(err);
                }

                const rootComments = results.map(row => row.comment_id);
                let remaining = rootComments.length;

                if (remaining === 0) {
                    // 删除留言
                    const sqlDeleteArticle = 'DELETE FROM blog_articles WHERE article_id = ?';
                    db.query(sqlDeleteArticle, [articleId], (err, results) => {
                        if (err) {
                            return res.cc(err);
                        }
                        if (results.affectedRows !== 1) {
                            return res.cc('删除留言失败');
                        }
                        res.send({
                            status: 0,
                            message: '删除留言成功'
                        });
                    });
                } else {
                    rootComments.forEach(commentId => {
                        deleteCommentsRecursively(commentId, (err) => {
                            if (err) {
                                return res.cc(err);
                            }
                            remaining--;
                            if (remaining === 0) {
                                // 删除留言
                                const sqlDeleteArticle = 'DELETE FROM blog_articles WHERE article_id = ?';
                                db.query(sqlDeleteArticle, [articleId], (err, results) => {
                                    if (err) {
                                        return res.cc(err);
                                    }
                                    if (results.affectedRows !== 1) {
                                        return res.cc('删除留言失败');
                                    }
                                    res.send({
                                        status: 0,
                                        message: '删除留言成功'
                                    });
                                });
                            }
                        });
                    });
                }
            });
        });
    });
}


// 删除评论
exports.deleteComments = (req, res) => {
    const { commentId, userId } = req.body;
    if (!commentId || !userId) {
        return res.cc('评论ID和用户ID不能为空');
    }

    // 查询评论作者ID
    const sqlCheckAuthor = 'SELECT user_id FROM blog_comments WHERE comment_id = ?';
    db.query(sqlCheckAuthor, [commentId], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        if (results.length !== 1) {
            return res.cc('评论不存在');
        }

        const authorId = results[0].user_id;

        // 验证用户身份：评论作者 或 blog_users 表中 ID 小于 10 的用户
        const sqlCheckUser = 'SELECT id FROM blog_users WHERE id = ? AND (id < 10 OR id = ?)';
        db.query(sqlCheckUser, [userId, authorId], (err, results) => {
            if (err) {
                return res.cc(err);
            }
            if (results.length !== 1) {
                return res.cc('没有删除权限');
            }

            // 递归删除评论及其所有子评论
            deleteCommentsRecursively(commentId, (err) => {
                if (err) {
                    return res.cc(err);
                }
                res.send({
                    status: 0,
                    message: '删除评论成功'
                });
            });
        });
    });
}

// 根据关键字搜索对应的留言
exports.searchArticles = (req, res) => {
    const { keyword } = req.query;
    if (!keyword) {
        return res.cc('关键字不能为空');
    }

    const sql = `
        SELECT 
            * 
        FROM 
            blog_articles 
        WHERE 
            title LIKE ? 
            OR content LIKE ? 
            OR author_id IN (SELECT id FROM blog_users WHERE username LIKE ? OR nickname LIKE ?)
        ORDER BY 
            likes DESC;
    `;

    const likeKeyword = `%${keyword}%`;
    db.query(sql, [likeKeyword, likeKeyword, likeKeyword, likeKeyword], (err, results) => {
        if (err) {
            return res.cc(err);
        }
        res.send({
            status: 0,
            message: '搜索留言成功',
            data: results
        });
    });
}

// 根据用户id查详细信息
exports.getUserInfoById = (req, res) => {
    const id = req.query.id;
    if (!id) {
        res.cc('查询用户信息不能为空')
    }
    const str = 'Select id, username, nickname, email from blog_users where id = ?'
    db.query(str, id, (err, results) => {
        // 执行sql失败
        if (err) return res.cc(err)
        //成功，但是查询结果为空
        if (results.length !== 1) return res.cc('获取用户信息失败')
        // 用户信息获取成功
        res.send({
            status: 0,
            message: '获取用户信息成功 ',
            data: results[0],
        })
    })
}